package com.fengze.business.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fengze.business.domain.FileInfo;
import com.fengze.business.domain.InquiryManifest;
import com.fengze.business.domain.ReimbursementList;
import com.fengze.business.enums.BusinessTypeEnums;
import com.fengze.business.mapper.FileInfoMapper;
import com.fengze.business.mapper.ReimbursementListMapper;
import com.fengze.common.annotation.AutoSetInsertValue;
import com.fengze.common.annotation.AutoSetUpdateValue;
import com.fengze.common.config.RuoYiConfig;
import com.fengze.common.utils.DateUtils;
import com.fengze.common.utils.SecurityUtils;
import com.fengze.common.utils.StringUtils;
import com.fengze.common.utils.file.FileUploadUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fengze.business.mapper.ReimbursementRecordMapper;
import com.fengze.business.domain.ReimbursementRecord;
import com.fengze.business.service.IReimbursementRecordService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 报销记录Service业务层处理
 *
 * @author lug
 * @date 2024-02-28
 */
@Service
public class ReimbursementRecordServiceImpl implements IReimbursementRecordService
{
    @Autowired
    private ReimbursementRecordMapper reimbursementRecordMapper;

    @Autowired
    private FileInfoMapper fileInfoMapper;


    @Autowired
    private ReimbursementListMapper reimbursementListMapper;
    /**
     * 查询报销记录
     *
     * @param id 报销记录主键
     * @return 报销记录
     */
    @Override
    public ReimbursementRecord selectReimbursementRecordById(Long id)
    {

        ReimbursementRecord reimbursementRecord = reimbursementRecordMapper.selectReimbursementRecordById(id);
        List<FileInfo> fileInfos = fileInfoMapper.selectListByBusiIdAndType(id,BusinessTypeEnums.REIMBURSEMENT.getCode());
        reimbursementRecord.setFileInfoList(fileInfos);
        List<ReimbursementList> reimbursementLists = reimbursementListMapper.selectByRecordId(id);
        reimbursementRecord.setReimbursementLists(reimbursementLists);
        return reimbursementRecord;
    }

    /**
     * 查询报销记录列表
     *
     * @param reimbursementRecord 报销记录
     * @return 报销记录
     */
    @Override
    public List<ReimbursementRecord> selectReimbursementRecordList(ReimbursementRecord reimbursementRecord)
    {
        return reimbursementRecordMapper.selectReimbursementRecordList(reimbursementRecord);
    }

    /**
     * 新增报销记录
     *
     * @param reimbursementRecord 报销记录
     * @return 结果
     */
    @Override
    public int insertReimbursementRecord(ReimbursementRecord reimbursementRecord)
    {
        reimbursementRecord.setCreateTime(DateUtils.getNowDate());
        return reimbursementRecordMapper.insertReimbursementRecord(reimbursementRecord);
    }

    /**
     * 修改报销记录
     *
     * @param reimbursementRecord 报销记录
     * @return 结果
     */
    @Override
    public int updateReimbursementRecord(ReimbursementRecord reimbursementRecord)
    {
        reimbursementRecord.setUpdateTime(DateUtils.getNowDate());
        return reimbursementRecordMapper.updateReimbursementRecord(reimbursementRecord);
    }

    /**
     * 批量删除报销记录
     *
     * @param ids 需要删除的报销记录主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteReimbursementRecordByIds(Long[] ids)
    {
        // 逻辑删除附件
        fileInfoMapper.deleteLogicalByBusiIdListAndType(ids,BusinessTypeEnums.REIMBURSEMENT.getCode(),1);
        reimbursementListMapper.deleteByRecordIds(ids);
        return reimbursementRecordMapper.deleteReimbursementRecordByIds(ids);
    }

    /**
     * 删除报销记录信息
     *
     * @param id 报销记录主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteReimbursementRecordById(Long id)
    {
        // 逻辑删除附件
        fileInfoMapper.deleteLogicalByBusiIdAndType(id,BusinessTypeEnums.REIMBURSEMENT.getCode(),1);
        reimbursementListMapper.deleteByRecordId(id);
        return reimbursementRecordMapper.deleteReimbursementRecordById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @AutoSetInsertValue
    @Override
    public int insertReimbursementRecordWithFiles(ReimbursementRecord reimbursementRecord, MultipartFile[] files) {
        reimbursementRecord.setStatus(0);

        BigDecimal money = new BigDecimal(0);
        String reimbursementListStr = reimbursementRecord.getReimbursementListStr();
        List<ReimbursementList> list = null;
        if (StringUtils.isNotEmpty(reimbursementListStr)) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, ReimbursementList.class);
                list = mapper.readValue(reimbursementListStr,listType);
                for (ReimbursementList reimbursementList : list) {
                    money = money.add(reimbursementList.getMoney());
                }

            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        reimbursementRecord.setMoney(money);
        int insertCount = reimbursementRecordMapper.insertReimbursementRecord(reimbursementRecord);
        if (CollectionUtils.isNotEmpty(list)) {
            for (ReimbursementList reimbursementList : list) {
                reimbursementList.setRecordId(reimbursementRecord.getId());
            }
            reimbursementListMapper.insertBatch(list);
        }



        if (null != files && files.length > 0) {
            for (MultipartFile file : files) {
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = null;
                try {
                    fileName = FileUploadUtils.upload(filePath, file);
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setStatus(0);
                    fileInfo.setBusiId(reimbursementRecord.getId());
                    fileInfo.setBusiType(BusinessTypeEnums.REIMBURSEMENT.getCode());
                    fileInfo.setFileName(file.getOriginalFilename());
                    fileInfo.setFileType(FileUploadUtils.getExtension(file));
                    fileInfo.setFileSize(file.getSize());
                    fileInfo.setFileUrl(fileName);
                    fileInfoMapper.insertFileInfo(fileInfo);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        return insertCount;
    }

    @AutoSetUpdateValue
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateReimbursementRecordWithFiles(ReimbursementRecord reimbursementRecord, MultipartFile[] files) {

        String deleteFileInfoIdStr = reimbursementRecord.getDeleteFileInfoIdStr();
        if (StringUtils.isNotEmpty(deleteFileInfoIdStr)) {
            fileInfoMapper.updateStatusByIdStr(deleteFileInfoIdStr,1);
        }
        if (null != files && files.length > 0) {
            for (MultipartFile file : files) {
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = null;
                try {
                    fileName = FileUploadUtils.upload(filePath, file);
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setStatus(0);
                    fileInfo.setBusiId(reimbursementRecord.getId());
                    fileInfo.setBusiType(BusinessTypeEnums.REIMBURSEMENT.getCode());
                    fileInfo.setFileName(file.getOriginalFilename());
                    fileInfo.setFileType(FileUploadUtils.getExtension(file));
                    fileInfo.setFileSize(file.getSize());
                    fileInfo.setFileUrl(fileName);
                    fileInfoMapper.insertFileInfo(fileInfo);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        // 删除数据库存储的数据
        reimbursementListMapper.deleteByRecordId(reimbursementRecord.getId());


        BigDecimal money = new BigDecimal(0);
        String reimbursementListStr = reimbursementRecord.getReimbursementListStr();
        List<ReimbursementList> list = null;
        if (StringUtils.isNotEmpty(reimbursementListStr)) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, ReimbursementList.class);
                list = mapper.readValue(reimbursementListStr,listType);
                if (CollectionUtils.isNotEmpty(list)) {
                    for (ReimbursementList reimbursementList : list) {
                        reimbursementList.setRecordId(reimbursementRecord.getId());
                        money = money.add(reimbursementList.getMoney());
                    }
                    reimbursementListMapper.insertBatch(list);
                }
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        reimbursementRecord.setMoney(money);
        int updateCount = reimbursementRecordMapper.updateReimbursementRecord(reimbursementRecord);
        return updateCount;
    }

    @Override
    public int examineInfo(Long id) {
        Long userId = SecurityUtils.getUserId();
        Date now = Calendar.getInstance().getTime();
        return reimbursementRecordMapper.updateAuditInfo(id,userId,now,1);
    }

    @Override
    public int paymentMoney(Long id) {
        Long userId = SecurityUtils.getUserId();
        Date now = Calendar.getInstance().getTime();
        return reimbursementRecordMapper.updatePaymentInfo(id,userId,now,2);
    }
}
